package com.tjhk.java.tech.thread.delay;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayedTask implements Runnable, Delayed {
    private static int counter = 0;
    private final int id = counter++;
    private final int delta;
    private final long trigger;
    protected static List<DelayedTask> sequence = new ArrayList<>();
    public DelayedTask(int delayInMilliseconds) {
        this.delta = delayInMilliseconds;
        this.trigger = System.nanoTime()
                +TimeUnit.NANOSECONDS.convert(delta,TimeUnit.MILLISECONDS);
        sequence.add(this);
    }

    @Override
    public int compareTo(Delayed o) {
        DelayedTask that = (DelayedTask)o;
        if (trigger < that.trigger) return -1;
        if (trigger > that.trigger) return 1;
        return 0;
    }

    @Override
    public void run() {
        System.out.println(this + " ");
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(trigger - System.nanoTime(),TimeUnit.NANOSECONDS);
    }

    @Override
    public String toString() {
        return String.format("[%d] Task %d",delta,id);
    }
    public String summary() {
        return String.format("(%d,%d)",id,delta);
    }
    public static class EndTask extends DelayedTask {
        public EndTask(int delayInMilliseconds) {
            super(delayInMilliseconds);
        }

        @Override
        public void run() {
            sequence.forEach(dt->{
                System.out.println(dt.summary());
            });
        }
    }
}
